const fs = require('fs')
const exApp = require('../index.js')
const express = require('express');
const router = express.Router();
const mysql = require("../connect/pomsql")
const multer = require('multer')
const path = require('path');
const upload = multer({ dest: path.join(path.dirname(__dirname), '../public', 'publishImgs') })
const { SuccessModule, ErrorModule } = require('../model/resModel');
router.get("/api/publish", async (req, res, next) => {
  let { big_type } = req.query;
  let data = await mysql(`SELECT * FROM  publish WHERE big_type='${big_type}' ORDER BY id DESC`)
  res.json({
    code: 200,
    data
  })
})
router.post("/api/publish/upload", upload.array('files', 6), async (req, res, next) => {
  let { nick_name, nick_attr, fans, follow, price, title, des, type, fabulous, tc_comment, see, big_type, img_url } = req.body
  let data = await mysql(`INSERT INTO publish(nick_name,nick_attr,fans,follow,price,title,des,type,fabulous,tc_comment,see,big_type,img_url) VALUES('${nick_name}','${nick_attr}','${fans}','${follow}','${price}','${title}','${des}','${type}','${fabulous}','${tc_comment}','${see}','${big_type}','${JSON.stringify(img_url)}')`)
  if (req.files) {
    console.log(111)
    req.files.map(item => {
      fs.rename(item.path, item.originalname, (err) => {
        if (err) throw err;
      })
    })
  }
  res.json({
    code: 200,
    msg: '添加成功'
  })
})

router.post("/api/publish/img/upload", upload.array('files', 6), async (req, res, next) => {
  console.log(req.files)
  req.files.map(item => {
    fs.rename(item.path, item.originalname, (err) => {
      if (err) throw err;
    })
  })
  res.json({
    code: 200,
    msg: '添加成功'
  })
})

router.get("/api/publish/type", async (req, res, next) => {
  let { type, big_type } = req.query
  // console.log(type)
  let data = await mysql(`SELECT * FROM publish WHERE type='${type}'AND big_type='${big_type}' ORDER BY id DESC`)
  res.json({ code: 200, data, })
})

router.put("/api/publish/update", async (req, res, next) => {

})

exApp.use('/', router);